<template>
    <el-form
        ref="ruleFormRef"
        style="max-width: 100%"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
    >
        <el-form-item label="客户编码" prop="code">
            <el-input v-model="ruleForm.code" placeholder="请输入客户编码" :disabled="ruleForm.id !== 0"/>
        </el-form-item>
        <el-form-item label="客户名称" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入客户名称"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNum">
            <el-input v-model="ruleForm.phoneNum" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="地址" prop="address">
            <el-input v-model="ruleForm.address" placeholder="请输入地址"/>
        </el-form-item>
        <el-form-item label="业务地区" prop="area">
            <el-input v-model="ruleForm.area" placeholder="请输入业务地区"/>
        </el-form-item>
        <el-form-item label="交易金额" prop="moneyValue">
            <el-input v-model.number="ruleForm.moneyValue" type="number" placeholder="请输入交易金额" step="0.01"/>
        </el-form-item>
        <el-form-item label="欠款额度" prop="creditLimit">
            <el-input v-model.number="ruleForm.creditLimit" type="number" placeholder="请输入欠款额度" step="0.01"/>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm()">提交</el-button>
            <el-button @click="emitCancel">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import {reactive, ref, watch} from 'vue';
import type {ComponentSize, FormInstance, FormRules} from 'element-plus';
import type {Customer} from "@/types/public-xs/Customer.ts";
import {ElMessage} from 'element-plus';
import request from "@/util/request.ts";

// 定义 validator 类型
type Validator = (
    rule: any,
    value: string,
    callback: (error?: Error) => void
) => void;

const emit = defineEmits(['submit-success', 'cancel']);


const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<Customer>({
    id: 0,
    code: '',
    name: '',
    area: '',
    address: '',
    createdBy: 0,
    createDate: '',
    updateId: '',
    updateDate: '',
    moneyValue: 0,
    phoneNum: '',
    isDelete: 0,
    creditLimit: 0
});

const originalCode = ref<string>('');

// 校验客户编码唯一性
const checkCode: Validator = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请输入客户编码'));
        return;
    }

    if (ruleForm.id !== 0 && value === originalCode.value) {
        callback();
        return;
    }

    request.post(`/basic/Customer/selectCustomerByCode?code=${value}`)
        .then(response => {
            if (response.data.code !== "200") {
                callback(new Error(response.data.msg || '接口返回错误'));
                return;
            }

            if (response.data.data) {
                callback(new Error('客户编码已存在'));
            } else {
                callback();
            }
        })
        .catch(error => {
            console.error('校验客户编码失败:', error);
            callback(new Error('校验客户编码失败，请稍后重试'));
        });
};

const rules = reactive<FormRules<Customer>>({
    code: [
        {required: true, message: '请输入客户编码', trigger: ['blur', 'change']},
        {min: 3, max: 10, message: '客户编码长度应为3到10个字符', trigger: ['blur', 'change']},
        {validator: checkCode, trigger: "blur"}
    ],
    name: [
        {required: true, message: '请输入客户名称', trigger: ['blur', 'change']},
        {min: 2, max: 50, message: '客户名称长度应为2到50个字符', trigger: ['blur', 'change']}
    ],
    phoneNum: [
        {required: true, message: '请输入手机号', trigger: ['blur', 'change']},
        {pattern: /^1[3-9]\d{9}$/, message: '请输入有效的11位手机号', trigger: ['blur', 'change']}
    ],
    address: [
        {required: true, message: '请输入地址', trigger: ['blur', 'change']},
        {max: 100, message: '地址长度不能超过100个字符', trigger: ['blur', 'change']}
    ],
    area: [
        {max: 100, message: '业务地区长度不能超过100个字符', trigger: ['blur', 'change']}
    ],
    moneyValue: [
        {required: true, message: '请输入交易金额', trigger: ['blur', 'change']},
        {type: 'number', min: 0, message: '交易金额必须为非负数', trigger: ['blur', 'change']}
    ],
    creditLimit: [
        {type: 'number', min: 0, message: '欠款额度必须为非负数', trigger: ['blur', 'change']}
    ]
});


const props = defineProps<{
    customer?: Customer | null;
}>();

watch(() => props.customer, (newCustomer) => {
    if (newCustomer) {
        Object.assign(ruleForm, {
            ...newCustomer,
            createdBy: Number(localStorage.getItem("userId") || "0"),
            updateId: localStorage.getItem("userId") || ""
        });
        originalCode.value = newCustomer.code;
    } else {
        originalCode.value = '';
        Object.assign(ruleForm, {
            id: 0,
            code: '',
            name: '',
            area: '',
            address: '',
            createdBy: 0,
            createDate: '',
            updateId: '',
            updateDate: '',
            moneyValue: 0,
            phoneNum: '',
            isDelete: 0,
            creditLimit: 0
        });
    }
}, {immediate: true});

const submitForm = async () => {
    if (!ruleFormRef.value) return;
    await ruleFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                const url = ruleForm.id ? '/basic/Customer/updateCustomer' : '/basic/Customer/insertCustomer';
                const response = await request.post(url, ruleForm);
                if (response.data.code === '200') {
                    ElMessage.success(ruleForm.id ? '更新客户成功' : '新增客户成功');
                    resetForm();
                    emit('submit-success');
                } else {
                    ElMessage.error(response.data.msg || '操作失败');
                }
            } catch (error) {
                ElMessage.error('操作失败，请稍后重试');
                console.error('操作失败:', error);
            }
        } else {
            ElMessage.warning('请完善表单信息');
        }
    });
};

const resetForm = () => {
    if (!ruleFormRef.value) return;
    ruleFormRef.value.resetFields();
};

const emitCancel = () => {
    emit('cancel');
};
</script>

<style scoped>
.demo-ruleForm {
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.el-input input[type="number"]::-webkit-inner-spin-button,
.el-input input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

.el-input input[type="number"] {
    -moz-appearance: textfield;
}
</style>
